﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Storage;

namespace Simple.Common.Uow.Uow
{
    public class UnitOfWork : IUnitOfWork
    {
        private bool disposed = false;
        private List<DbContext> _dbContexts=new List<DbContext>();

        public UnitOfWork()
        {
            if (!_dbContexts.Any())
            {
                _dbContexts = new List<DbContext>();
            }
        }

        /// <summary>
        /// Appends the database context.
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        public async Task AppendDbContext(DbContext dbContext)
        {
            await AppendDbContext(new List<DbContext> { dbContext });
        }
        public async Task AppendDbContext(List<DbContext> dbContexts)
        {
            _dbContexts.AddRange(dbContexts);
            _dbContexts = _dbContexts.Distinct().ToList();
            await Task.CompletedTask;
        }
        #region Commit

        public async virtual Task CommitAsync()
        {
            await CrossCommitAsync();
        }
        private async Task CrossCommitAsync()
        {
            List<IDbContextTransaction> list = new List<IDbContextTransaction>();
            try
            {
                foreach (var context in _dbContexts)
                {
                    IDbContextTransaction item = context.Database.BeginTransaction();
                    await context.SaveChangesAsync();
                    list.Add(item);
                }
                foreach (IDbContextTransaction transaction in list)
                {
                    await transaction.CommitAsync();
                }
            }
            catch (Exception ex)
            {
                foreach (var transaction in list)
                {
                    await transaction.RollbackAsync();
                }
                throw ex;
            }
            finally
            {
                foreach (IDbContextTransaction transaction in list)
                {
                    await transaction.DisposeAsync();
                }
            }
        }
        #endregion Commit

        #region ExecuteSqlInterpolated
        public async Task<int> ExecuteSqlRawAsync<TDbContext>(string sql) where TDbContext : DbContext
        {
            TDbContext context = (TDbContext)Activator.CreateInstance(typeof(TDbContext));
            return await context.Database.ExecuteSqlRawAsync(sql);
        }
        public async Task<int> ExecuteSqlRawAsync<TDbContext>(string sql, params object[] parameters) where TDbContext : DbContext
        {
            TDbContext context = (TDbContext)Activator.CreateInstance(typeof(TDbContext));
            return await context.Database.ExecuteSqlRawAsync(sql, parameters);
        }

        #endregion ExecuteSqlCommand

        public  async ValueTask DisposeAsync()
        {
            await DisposeAsyncCore();
            GC.SuppressFinalize(this);
        }
        protected virtual async ValueTask DisposeAsyncCore()
        {
            foreach (var context in _dbContexts)
            {
                await context.DisposeAsync();
            }
            _dbContexts.Clear();
        }
    }
}
